package eerbaar.internal.elements.extension;

import java.util.ArrayList;
import java.util.List;

import eerbaar.elements.extension.ILeaderElement;
import eerbaar.elements.extension.IPackMemberElement;
import eerbaar.elements.extension.IPackMemberListener;
import eerbaar.extension.IExtensible;

public class PackMemberElementImpl implements IPackMemberElement {

    private final IExtensible parent;
    private ILeaderElement leader;
    private final List<IPackMemberListener> listeners = new ArrayList<IPackMemberListener>();

    public PackMemberElementImpl(IExtensible parent) {
        this.parent = parent;
    }

    @Override
    public void addListener(IPackMemberListener listener) {
        if (!this.listeners.contains(listener)) {
            this.listeners.add(listener);
        }
    }

    @Override
    public IExtensible copy() {
        return new PackMemberElementImpl(this.parent);
    }

    private void firePackJoined() {
        for (IPackMemberListener l : this.listeners) {
            l.onPackJoined();
        }
    }

    private void firePackLeft() {
        for (IPackMemberListener l : this.listeners) {
            l.onPackLeft();
        }
    }

    @Override
    public <T extends IExtensible> T getExtension(Class<T> type) {
        return this.parent.getExtension(type);
    }

    @Override
    public ILeaderElement getLeader() {
        return this.leader;
    }

    @Override
    public void removeListener(IPackMemberListener listener) {
        if (this.listeners.contains(listener)) {
            this.listeners.remove(listener);
        }
    }

    @Override
    public void setLeader(ILeaderElement leader) {

        this.leader = leader;

        if (this.leader == null) {
            firePackLeft();
        } else {
            firePackJoined();
        }
    }

}
